package com.luck.easyfoodbatch.mvp.home;

import android.content.Context;
import android.support.annotation.Nullable;

import com.luck.easyfoodbatch.callback.JsonCallback;
import com.luck.easyfoodbatch.mvp.model.ClassModel;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.cache.CacheMode;
import com.lzy.okhttputils.model.HttpParams;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * author：luck
 * project：EasyFoodBatch
 * package：com.luck.easyfoodbatch.mvp.home
 * email：893855882@qq.com
 * data：16/10/25
 */
public class ClassListsPresenter implements ClassListsModel {

    private final String TAG = getClass().getSimpleName();
    private ClassListsView classListsView;
    private Context mContext;

    public ClassListsPresenter(ClassListsView classListsView, Context mContext) {
        this.classListsView = classListsView;
        this.mContext = mContext;
    }


    @Override
    public void getClassList(int type, int isRefresh, String limit) {
        HttpParams params = new HttpParams();
        params.put("limit", limit);
        CacheMode mode = CacheMode.DEFAULT;
        if (type == 1) {
            // 上新选择商品

        } else {
            switch (isRefresh) {
                case 0:
                    // 下拉刷新
                    mode = CacheMode.FIRST_CACHE_THEN_REQUEST;
                    break;
                case 1:
                    mode = CacheMode.REQUEST_FAILED_READ_UPDATE_CACHE;
                    break;
            }
        }
        OkHttpUtils.post(HttpUtil.CLASS_LISTS)
                .tag(this)
                .cacheMode(mode)
                .cacheKey(TAG + limit)
                .params(params)
                .cacheTime(1800)
                .execute(new JsonCallback(mContext, ClassModel.class) {

                    @Override
                    public void onResponse(boolean isFromCache, Object data, Request request, @Nullable Response response) {
                        classListsView.getHomeClassSuccess((ClassModel) data);
                        classListsView.hideLoading();
                    }

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                        classListsView.hideLoading();
                        classListsView.httpStatusError();
                    }
                });
    }
}
